//var orderInfoUrl = PurchaseAppConfig.Domain +"/splitCart/splitCart.action";
var orderInfoUrl = "http://cart.en.jd.com/order/orderInfoMainEPT.html";
/**
 * 购物车操作请求服务器Call
 * @param url
 * @param param
 * @param errorMessage
 * @param callback
 */ 
function call(url,param,errorMessage,callback){
	var outSkus = $("#outSkus").val();
	jQuery.ajax({ 
		type : "POST",
		dataType : "json",
		url : url,
		data : param+"&outSkus="+outSkus+"&random="+Math.random(),
		success : function(result) {
			if(result != null && result.success){
				$("#show-cart").hide().remove();
				initCart(result);
				if(callback != null){
					callback();
				}
				//重新设置无货商品列表
				if(result.outSkus != null && result.outSkus != ""){
					$("#outSkus").val(result.outSkus);
				}
//				setArea();
//				initYanBao();
				if(result.addSkuLimitState != null && result.addSkuLimitState != ""){
					if(result.addSkuLimitState == "Add_Item_Fail" ){
						alert("Your shopping cart has exceed the number of items allowed!");
					}
				}
			}else if(result.errorMessage == "Not_Have_CartStore"){//取出操作时，如没有寄存商品，不提示
			}else{
				if($("#cart-loading-dialog").css("display") != null && $("#cart-loading-dialog").css("display") != "none"){
					$("#cart-loading-dialog").hide();
				}
				if(result.errorMessage != null && result.errorMessage != ""){
//					alert(result.errorMessage);
					alert("The network is busy, please try again later!");
				}else{
					alert("System error, please try again later!");
				}
			}
		},
		error:function(XMLHttpResponse){}
		
	});
}
/**
 * 修改购物车商品
 * @param url
 * @param pid
 * @param ptype
 * @param packId
 * @param targetId
 * @param errorMessage
 * @param callback
 */
function updateCart(url,pid,ptype,packId,targetId,errorMessage,callback){
	jQuery.ajax({ 
		type : "POST",
		dataType : "json",
		url : url+"&pid="+escape(pid)+"&ptype="+escape(ptype)+"&packId="+escape(packId)+"&targetId="+escape(targetId),
		data:null,
		success : function(result) {
			if(result != null && result.success){
				$("#show-cart").hide().remove();
				initCart(result);
				if(callback != null){
					callback();
				}
//				setArea();
//				initYanBao();
			}else if(result.errorMessage == "Not_Have_CartStore"){//取出操作时，如没有寄存商品，不提示
			}else{
				//服务端返回的错误信息
				if($("#cart-loading-dialog").css("display") != null && $("#cart-loading-dialog").css("display") != "none"){
					$("#cart-loading-dialog").hide();
				}
				if(errorMessage != null && errorMessage != ""){
					alert(errorMessage);
				}
			}
		},
		error:function(XMLHttpResponse){}
	});
}

/**
 * 取消删除恢复商品数量
 */
function backSkuNumber(){
	//---如果是改变文本框数量为0，取消后需要恢复之前的数量
	var beforeId=$("#changeBeforeId").val();
	var beforeNumber=$("#changeBeforeValue").val();
	if(beforeId != null && 
	   beforeId != "" &&
	   beforeNumber !=null &&
	   beforeNumber != ""){
	   var nowNumber=$("#"+beforeId).val();
	   if(nowNumber == "0" || nowNumber == 0){
		   $("#"+beforeId).val(beforeNumber);
		   $("#changeBeforeId").val("");
		   $("#changeBeforeValue").val("");
	   }
	}
}


/**
 * 异步获取延保信息
 */
function initYanBao(){
	if(isEmptyCart()){
		return ;
	}
	jQuery.ajax({
		type : "POST",
		dataType : "json",
		url : PurchaseAppConfig.Domain+"/queryProductYb.action"+"?random="+Math.random(),
		data : null,
		success : function(result) {
		   var data = TrimPath.processDOMTemplate("cart_skuYb_jst", result); 
		   document.getElementById("sku_yb_div").innerHTML = data;
		   var productYbInfos=result.productYbInfos;
		   if(productYbInfos != null && productYbInfos.length>0){
			   $(".sku-yanBao").each(function(){
					var skuInfos=$(this).attr("data").split("_");
					var wid=skuInfos[1];
					var suitId=skuInfos[2];	
					for(var i=0;i<productYbInfos.length;i++){
						var productYbInfo = productYbInfos[i];
						if(productYbInfo.suitId == suitId && productYbInfo.wid == wid){
							var ybDetail=$(this).siblings(".clearfix");
							//---如果有延保服务，并且没有选中情况下加载延保服务
							if(ybDetail != null && ybDetail.html()!= null){
								$("#updateYb_"+wid+"_"+suitId).show();
							}
							else{
							    $(this).html("<p class='extend-service-btn'>" +
							   "<a id='select-extend-service_"+wid+"_"+suitId+"' " +
							   "title='延保服务' clstag='clickcart|keycount|xincart|extendscopelink' href='javascript:void(0);'>延保服务</a>" +
							   "</p>");
							}
						  }
					}
				});
			   //延保弹出层
				$("[id^='select-extend-service']").bind("click", function(event){
					event.preventDefault();
					var o = $(this).offset();
					var t = o.top + $(this).outerHeight();
					var l = o.left;
					var skuId = $(this).attr("id").split("_")[1];
					var packId = $(this).attr("id").split("_")[2];
					var ybId = $(this).attr("id").split("_")[3];								
					$("#yb-radio_"+ybId+"_"+skuId+"_"+packId).attr("checked","checked");
					$("#extend-dialog_"+skuId+"_"+packId).css({
						"display": "block",
						"top": t,
						"left": l,
						"z-index": 1000
					});
				});
				//所有对话框中的取消
				$(".btn-cancel").click(function(){
					$(this).parents(".dialog").hide();
					backSkuNumber();
				});
				//所有对话框中的关闭
				$(".dialog-close").click(function(){
					$(this).parents(".dialog").hide();
				});
				
				//延保选择确认按钮
				$("[id^='yb-confirm_']").click(function(){
					var a = $(this).attr("id").split("_");
					var skuId = a[1];
					var packId = a[2];
					$("#extend-dialog_"+skuId).hide();
					var ybskuId = $("[name^='yb-radio_']:checked").val();
					var type = SkuItemType.YbOfSkusOrGifts;
					if(packId != null && packId != "" && packId != 0){
						type = SkuItemType.YbOfPacks;
					}
					$(this).parents(".dialog").hide();
					addYbSkuToCart(ybskuId,type,1,packId,skuId);
				});
		   }
	
		},
		error:function(XMLHttpResponse){
		
		}
	});
} 


/**
 * 初始化购物车，绑定各种事件
 * @param result
 */
function initCart(result){
	var data = TrimPath.processDOMTemplate("cart_jst", result); 
	document.getElementById("show").innerHTML = data;
	
	if(isAllCheck($.jCookie("cart-main"))){
		$("#toggle-checkboxes").attr("checked",true);
	}else{
		$("#toggle-checkboxes").attr("checked",false);
	}
	//TODO:loading弹窗隐藏,success弹窗显示
	
	
		
	replaceLoadingWithStockState(result);
	
	
	
	//checkbox的click事件
	toggleSelected();
	toggleSingleSelected();
	//库存弹出层
	$("#inventory").bind("click", function(){
		var o = $(this).offset();
		var t = o.top + $(this).outerHeight() + 2;
		var l = o.left;
		
		$("#inventory-dialog").css({
			"display": "block",
			"top": t,
			"left": l,
			"z-index": 1000
		});
	});
	
	//赠品弹出层
	$("[id^='select-gift']").bind("click", function(event){
		event.preventDefault();
		var o = $(this).offset();
		var t = o.top + $(this).outerHeight();
		var l = o.left;
		var skuId = $(this).attr("id").split("_")[1];
		
		$("#gift-dialog_"+skuId).css({
			"display": "block",
			"top": t,
			"left": l,
			"z-index": 1000
		});
	});
	//删除弹出层
	$("[id^='remove-']").bind("click", function(event){
		event.preventDefault();
		var o = $(this).offset();
		var t = o.top + $(this).outerHeight() + 3;
		var l = o.left + $(this).width() - $("#cart-delete-dialog").width();
		
		if($(this).attr("id")=="remove-batch"){//批量删除
			$(".cart-delete").html("Are you sure you want to clear your cart?");
			l = o.left;
		}
		else{
			$(".cart-delete").html("Are you sure you want to remove this item from your shopping cart?");
		}
		
		$("#cart-delete-dialog").css({
			"display": "block",
			"top": t,
			"left": l,
			"z-index": 1000
		});
		
		$("#btnRemoveConfirm").attr("data-bind",$(this).attr("id"));
		$("#btnRemoveConfirm").attr("data-name",$(this).attr("data-name"));
		$("#btnRemoveConfirm").attr("data-more",$(this).attr("data-more"));
	});
	
	//减少商品数量
	$("[id^='decrement-']").bind("click", function(event){
		minusSkuNum(this);
	});
	
	//增加商品数量
	$("[id^='increment-']").bind("click", function(event){
		addSkuNum(this);
	});
	
	//商品数量文本框获取焦点，保存之前的值
	$("[id^='changeQuantity-']").bind("focus", function(event){
		var number=$(this).val();
		if(isNaN(number)){
			return ;
		}
		else{
			if(number != "0"){
				$("#changeBeforeValue").val(number);
				$("#changeBeforeId").val($(this).attr("id"));
			}
		}
	});
	
	
	//改变商品数量
	$("[id^='changeQuantity-']").bind("change", function(event){
		if($(this).val() == null || $(this).val() == ""){
			popupFormatWarningDialog(this,"This is a required field!");
			return;
		}
		if(isNaN($(this).val()) || $(this).val() == null || $(this).val() == "" ){//不是数字
			popupFormatWarningDialog(this,"You can only enter numbers in this field!");
			return;
		}
		inputSkuNum(this);
	});
	
	//所有对话框中的取消
	$(".btn-cancel").click(function(){
		$(this).parents(".dialog").hide();//父辈元素中class为dialog的div隐藏
		backSkuNumber();
	});
	//所有对话框中的关闭
	$(".dialog-close").click(function(){
		$(this).parents(".dialog").hide();
	});
	
	$("#btnRemoveConfirm").removeAttr("disabled");
	
	//删除确认按钮
	$("#btnRemoveConfirm").unbind().bind("click",function(){
		$(this).attr("disabled","true");
		$("#cart-delete-dialog").hide();
		//批量删除
		if($(this).attr("data-bind")=="remove-batch"){
			var selected = $(".item_selected");
			if(selected != null && selected.length != 0){//如果有选中商品
				var html = "";
				$("#product-list").children(".item.item_selected").each(function(){//所有选中单品
					var item = $(this).find("[id^='remove-']");
					if(item != null){
						var id = item.attr("id").split("-")[1];
						var name = item.attr("data-name");
						var ss = item.attr("data-more").split("-");
						var price = ss[1];
						var num = ss[2];
						html += "<div class='r-item clearfix' id='removedShow-"+id+"'>"
						+"<div class='r-name'><a href='http://en.jd.com/product/"+id+".html'>"+name+"</a></div>"
						+"<div class='r-price'>US&#36; "+price+"</div>"
						+"<div class='r-quantity'>&nbsp;</div>"
						+"<div class='r-control'><a href='javascript:void(0);' id='removedBuy-"+id+"' clstag='clickcart|keycount|xincart|reAddedSku' onclick='removedBuy("+id+","+num+")'>Add to Cart</a><span></span><a href='javascript:void(0);' clstag='clickcart|keycount|xincart|SaveFavorite' onclick='saveConcern("+id+")'>Add to My wish list</a></div>"
						+"</div><span class=\"clr\"></span>";
					}
				});
				$(".cart-removed").append(html);
				
				if(html != ""){
					batchRemoveSkusFromCart(showCartRemoved);
				}else{
					batchRemoveSkusFromCart();
				}
			}else{
				alert('Please enter at least one product!');
			}
			return ;
		}
		var ss = $(this).attr("data-bind").split("-");
		var id = ss[1];
		var type = ss[2];
		var targetId = 0;
		var packId = 0;
		if(ss.length==4){
			targetId = ss[3];
		}else if(ss.length==5){
			targetId = ss[3];
			packId = ss[4];
		}
		
		if(type==SkuItemType.Sku){//单品 删除商品要重新显示
			log( 7,1,id );//删除商品统计
			$("#removedShow-"+id).remove();//有重复的先删掉
			var name = $(this).attr("data-name");
			ss = $(this).attr("data-more").split("-");
			
			var price = ss[1];
			var num = ss[2];
			var data = "<div class='r-item clearfix' id='removedShow-"+id+"'>"
				+"<div class='r-name'><a href='http://en.jd.com/product/"+id+".html'>"+name+"</a></div>"
				+"<div class='r-price'>US&#36; "+price+"</div>"
				+"<div class='r-quantity'>&nbsp;</div>"
				+"<div class='r-control'><a href='javascript:void(0);' id='removedBuy-"+id+"' onclick='removedBuy("+id+","+num+")'>Add to Cart</a><span></span><a href='javascript:void(0);' onclick='saveConcern("+id+")'>Add to My wish list</a></div>"
				+"</div><span class=\"clr\"></span>";
			$(".cart-removed").append(data);
			removeSku(id,type,packId,targetId,showCartRemoved);
		} else{
			removeSku(id,type,packId,targetId);
		}
	});
	
	//普通套装样式处理
	$(".suit").each(function(){
		//普通套装中最后一个单品要是实框
		$(".row:last", $(this) ).addClass("row-last");
	});
	
	//满返满赠样式处理
	$(".item-meet").each(function(){
		//满返还是满赠
		var type = $(this).children("input[type=hidden]").val();
		$(this).addClass(type);
		//满返满赠中最后一个单品要是实框
		$(".item:last", $(this) ).addClass("item-last");
	});
	
	//推荐和收藏
	$("#c-tabs").Jtab({
		type: "dynamic",
		event: "click",
		delay: 300
	});
	
	//继续购物
	var backurl = getParam("backurl");
	if(backurl!=null && backurl!=""){
		$("#continue").attr("href",backurl);
	}
	
	//寄存
	$(".btn-storage").click(function(){
		try {
			if (!isLogin()) {
				jdModelCallCenter.settings = {
					'fn' : function() {
						setLogin(true);
						storage();
					}
				};
				jdModelCallCenter.login();
			} else {
				storage();
			}
		} catch (e) {
		}
	});
	//取出
	$(".btn-takeout").click(function(){
		try {
			if (!isLogin()) {
				jdModelCallCenter.settings = {
					'fn' : function() {
						setLogin(true);
						takeout();
					}
				};
				jdModelCallCenter.login();
			} else {
				takeout();
			}
		} catch (e) {
		}
	});
}

/**
 * 重新购买--只限单品
 */
function removedBuy(id,num){
	addSkuToCartReBuy(id,1,num,0,0);
	$("#removedShow-"+id).remove();
	if($(".cart-removed").find(".r-item").attr("id")==null){
		$(".cart-removed").hide();
	}
}

/**
 * 寄存购物车中的商品
 */
function storage(){
	$.getJSON(PurchaseAppConfig.Domain+"/storage.action?rd="+Math.random(),function(result){
		if(result != null && result.success){
			alert("购物车中的商品已成功寄存");
		}else{
			alert("购物车寄存失败");
		}
	});
}

/**
 * 取出购物车中的商品
 */
function takeout(){
	call(PurchaseAppConfig.Domain+"/takeout.action?rd="+Math.random(),null,"取出购物车失败");
}

/**
 * 删除商品显示
 */
function showCartRemoved(){
	$(".cart-removed").show();
}

function initRecommendAndCollection(){
	//推荐
	if($("#ids").val()!=null && $("#ids").val() != ""){
		var $someBuy = $("#some-buy");
		var ipLocation = $.jCookie("ipLocation");
		someOtherWare($someBuy,ipLocation,$("#ids").val());
	}
	//收藏---暂时关闭
	/*if(isLogin()){
		var $moreRecent = $("#more-recent");
		moreRecent($moreRecent);
	}*/
}

/**
 * 将商品加到关注
 */
function saveConcern(skuId)
{
	try {
		if (!isLogin()) {
			jdModelCallCenter.settings = {
				'fn' : function() {
					setLogin(true);
					follow(skuId);
				}
			};
			jdModelCallCenter.login2();
		} else {
			follow(skuId);
		}
	} catch (e) {
	}
}

function follow(skuId){
	$.ajax({
        type: "GET",
        url: "http://t.jd.com/regard/follow.action?rd="+Math.random(),
        data: "goodId="+skuId,
        dataType:"jsonp",
        success: function(result){
            if(result.code=="success"||result.code=="E004")
                alert("You have successfully added this to your Wish List!");
            else
                alert("There was a problem added this item to your Wish List!");
        },
        error:function(result){
            alert("There was a problem added this item to your Wish List!");
        }
       }); 
}

/**
 * 判断cart是否全选
 */
function isAllCheck(cart){
	if(cart == null || cart == "") return false;
	cart = cart.replace(/\\/g,"");
	cart = cart.replace(/\"/g,"");
	cart = cart.substring(1,cart.length-1);
	if(cart.indexOf("&ct&:0") == -1){
		return true;
	}else{
		return false;
	};
}

/**
 * 到货通知弹层
 */
function productNotify(obj,id){
	var o = $(obj).offset();
	var t = o.top + $(obj).outerHeight() + 3;
	var l = o.left + $(obj).width() - $("#cart-notify-dialog").width();
	
	$("#cart-notify-dialog").css({
		"display": "block",
		"top": t,
		"left": l,
		"z-index": 1000
	});
	
	$("#notifyConfirm").attr("data-bind",id);
}

/**
 * 发送到货通知
 */
function sendNotify(obj){
	var productId = $(obj).attr("data-bind");
	var email = $(".notify-email").val();
	if(check_email(email)){
		//获取key
		$.getJSON(PurchaseAppConfig.Domain+"/getPassKey.action?pid="+productId+"&rd="+Math.random(),function(result){
			var key = result.notifyKey;
			var opType = 2;
			//发送通知
			jQuery.ajax({
				type: "get",
				dataType : "jsonp",   
				url:"http://notify.home.jd.com/addNotifyInterface.action?callback=?",
				data: {
				    skuid: productId,
				    type:opType,
				    email:escape(email),
				    key:key,
				    userSource:"2"
				},
				success: function(json) { 
					if(json!=null && json.result){
						alert("申请到货通知成功");
						$("#cart-notify-dialog").hide();
					}else{
						alert(json==null?"申请到货通知失败":json.message);
					}
				},
				error: function(XMLHttpRequest){
					alert("申请到货通知失败");
				}
			});
		});
	}else{
		alert("邮箱格式不正确");
	}
}

/**
 * 检查邮箱格式
 * @param email
 * @returns {Boolean}
 */
function check_email(email)
{  
   if(email){
   var myReg=/(^\s*)\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*(\s*$)/;
   if(!myReg.test(email)){return false;}
   return true;
   }
   return false;
}

/**
 * 判断是否登录
 * @returns {Boolean}
 */
function isLogin(){
	var isLogin = $("#isLogin").val();
	if(isLogin == 1){
		return true;
	}else{
		return false;
	}
}

/**
 * 设置登录标记
 * @param flag
 */
function setLogin(flag){
	var isLogin = flag ? "1" : "0";
	$("#isLogin").val(isLogin);
}

/**
 * 跳转到订单页如未登录弹出登录弹窗
 */
function goToOrder(){
	var selected = $(".item_selected");
	if(selected != null && selected.length != 0){
		
		var ret = false;
		jQuery.ajax({ 
			type : "POST",
			dataType : "json",
			url : PurchaseAppConfig.Domain+"/getCurrentCartNew.action?rd="+Math.random(),
			async : false,
			success : function(result) {
				
				
				
				
				if(result != null && result.success){
					$("#show-cart").hide().remove();
					

					var stockStates = result.stockStates;
					if(stockStates != null && stockStates.length > 0){
						
						for(var i = 0 ; i <  stockStates.length ; i++ ){
							
							var stockState  = stockStates[i];
							if(stockState.state == '34'){
								initCart(result);
								ret = true;
								return;
							}
						}	
					}
				}
			},
			error:function(XMLHttpResponse){}
			
		});
		
		

		if(ret)
			return;
		
	   try {
			if(!isLogin()) {
				jdModelCallCenter.settings = {
					'url' : orderInfoUrl,
					'clstag1' : "login|keycount|5|5",
					'clstag2' : "login|keycount|5|6",
					'fn' : function() {
						jdModelCallCenter.autoLocation(this.url);
					}
				};
				jdModelCallCenter.login();
			} else {
				$('#toSettlement').hide();
				$('#toSettlement').after("<span class='checkout-state'>Please wait momentarily while we return to your Order Confirmation page.</span>");
				window.setTimeout('window.location.href = orderInfoUrl+"?rd="+Math.random();',3000);
				window.location.href = orderInfoUrl+"?rd="+Math.random();
			}
		} catch (e) {
			window.setTimeout('window.location.href = orderInfoUrl+"?rd="+Math.random();',1000);
			window.location.href = orderInfoUrl+"?rd="+Math.random();
		}
	}else{
		alert('Please enter at least one product!');
	}
	
} 

/**
 * 在原来加载中弹窗的位置弹出修改成功弹窗
 */
function replaceLoadingWithSuccess(adMessage){
	
	if($("#cart-loading-dialog").css("display") != null && $("#cart-loading-dialog").css("display") != "none"){
		$("#cart-loading-dialog").hide();
		//商品金额
		$("#finalPriceChanged").html("US&#36; "+$("#finalPrice").attr("data-bind"));
		//广告词
		if(adMessage != null && adMessage != ""){
			$("#adMessage").html(adMessage+"<br/>");
		}else{
			$("#adMessage").html("");
		}
		
		$("#cart-success-dialog").attr("style",$("#cart-loading-dialog").attr("style"));
		var top = parseInt($("#cart-loading-dialog").css("top").split("px")[0]) + parseInt($("#cart-loading-dialog").height()) - parseInt($("#cart-success-dialog").height());
		$("#cart-success-dialog").css("top",top);
		$("#closeSuccessDialog").click(function(){
			$("#cart-success-dialog").hide();
		});
		$("#cart-success-dialog").show();
		setTimeout("hideDialog('cart-success-dialog')",2000);
	}
}


/**
 * 在原来加载中弹窗的位置弹出修改成功弹窗
 */
function replaceLoadingWithStockState(result){
	
	
	var stockStates = result.stockStates;
	//alert(stockStates.length);
	if(stockStates != null && stockStates.length > 0){
		
		for(var i = 0 ; i <  stockStates.length ; i++ ){
			
			var stockState  = stockStates[i];
			var message = "";
			if(stockState.state == '34' && stockState.rNum == -1){
				
				message = "Sorry! We currently have not enough units available. Please either amend your quantity or email us at contact@jd.com and we can inform you when stock is available.";
			}else if(stockState.rNum > 0){
				
				message = "Sorry! We currently only have "+ stockState.rNum +" units available. Please either amend your quantity or email us at contact@jd.com and we can inform you when stock is available."
			}
			
			if(message != null && message != ""){
				
				if($("#cart-loading-dialog").css("display") != null && $("#cart-loading-dialog").css("display") != "none"){
					
					$("#cart-loading-dialog").hide();
				}

				var obj = $("[id^='changeQuantity-" +stockState.sku + "']");
				
				createAndPopupStockStateWarningDialog(obj, message, i);
				
					if(i == stockStates.length - 1){
						obj.focus();
					}
			}else{
				
				replaceLoadingWithSuccess(result.adMessage);
			}
		}
			
	}
	
	
	
}

/**
 * 库存不正确弹窗
 */
function popupStockStateWarningDialog(obj, message){
	
	$("#dialog-warning-notice").html(message);
	var o = $(obj).offset();
	var t = o.top - 150;
	var l = o.left + $(obj).width()/2 - $("#cart-format-warning-dialog").width()/2;
	
	$("#cart-format-warning-dialog").css({
		"display": "block",
		"top": t,
		"left": l,
		"z-index": 1000
	});
	window.setTimeout("hideDialog('cart-format-warning-dialog')",4000);
}


/**
 * 库存不正确弹窗
 */
function createAndPopupStockStateWarningDialog(obj, message, num){
	
	var dialogId = "cart-format-warning-dialog_"+num;
	
	var html = "<div id='"+dialogId+"' class='dialog cart-tooltip cart-tooltip-notice' style='display:none; left:710px; width:380px;'>"
				+"<div class='dialog-outer'>"
				+"<span class='dialog-bg dialog-bg-n'></span>"
				+"<span class='dialog-bg dialog-bg-ne'></span>"
				+"<span class='dialog-bg dialog-bg-e'></span>"
				+"<span class='dialog-bg dialog-bg-se'></span>"
				+"<span class='dialog-bg dialog-bg-s'></span>"

				+"<span class='dialog-bg dialog-bg-sw'></span>"
				+"<span class='dialog-bg dialog-bg-w'></span>"
				+"<span class='dialog-bg dialog-bg-nw'></span>"

				+"<div class='dialog-inner'>"
				+"<div class='dialog-content'>"
				+"<div class='dialog-notice'  id='"+dialogId+"'>"+message+"</div>"
				+"</div>"
				+"</div>"

				+"<div class='dialog-bump'><span class='dialog-arrow'></span></div>"
				+"</div>"
				+"</div>";
	
	$("#cart-format-warning-dialog").after(html);
	var o = $(obj).offset();
	var t = o.top - 100;
	var l = o.left + $(obj).width()/2 - $("#"+dialogId).width()/2;
	
	$("#"+dialogId).css({
		"display": "block",
		"top": t,
		"left": l,
		"z-index": 1000
	});
	window.setTimeout("removeDialog('"+dialogId+"')",4000);
}

/**
 * 数字格式不正确弹窗
 */
function popupFormatWarningDialog(obj,message){
	$("#dialog-warning-notice").html(message);
	var o = $(obj).offset();
	var t = o.top - 50;
	var l = o.left + $(obj).width()/2 - $("#cart-format-warning-dialog").width()/2;
	
	$("#cart-format-warning-dialog").css({
		"display": "block",
		"top": t,
		"left": l,
		"z-index": 1000
	});
	window.setTimeout("hideDialog('cart-format-warning-dialog')",2000);
}

/**
 * 修改延保商品数量提示弹窗
 */
function popupYbWarningDialog(obj,message){
	$("#dialog-warning-notice").html(message);
	var o = $(obj).offset();
	var t = o.top - 70;
	var l = o.left + $(obj).width()/2 - $("#cart-format-warning-dialog").width()/2;
	
	$("#cart-format-warning-dialog").css({
		"display": "block",
		"top": t,
		"left": l,
		"z-index": 1000
	});
	window.setTimeout("hideDialog('cart-format-warning-dialog')",2000);
}

/**
 * 限购弹窗
 */
function popupRestrictWarningDialog(obj,limitNum){
	$("#cart-success-dialog").hide();
	$("#limitNum").html(limitNum);
	var o = $(obj).offset();
	var t = o.top - 50;
	var l = o.left + $(obj).width()/2 - $("#cart-restrict-warning-dialog").width()/2;
	
	$("#cart-restrict-warning-dialog").css({
		"display": "block",
		"top": t,
		"left": l,
		"z-index": 1000
	});
	setTimeout("hideDialog('cart-restrict-warning-dialog')",2000);
}

/**
 * 加载中弹窗
 */
function popupLoadingDialog(obj){
	$("#cart-restrict-warning-dialog").hide();
	var o;
	if($(obj).attr("class")=="quantity-text"){
		o = $(obj).offset();
	}else{
		o = $(obj).siblings(".quantity-text").offset();
	}
	var t = o.top - 80;
	var l = o.left - $("#cart-loading-dialog").width()/2 + 18;
	
	$("#cart-loading-dialog").css({
		"display": "block",
		"top": t,
		"left": l,
		"z-index": 1000
	});
}

/**
 * 隐藏窗体
 * @param obj
 */
function hideDialog(obj){
	$("#"+obj).hide();
}

function removeDialog(obj){
	$("#"+obj).remove();
}

/**
 * 验证商品数量
 * @param obj
 * @param num
 * @param limit
 * @returns {Boolean}
 */
function isNumLegal(obj,num,limit){
	if(parseInt(num)==0){//删除商品
		var o = $(obj).offset();
		var t = o.top + $(obj).outerHeight() + 3;
		var l = o.left + $(obj).width() - $("#cart-delete-dialog").width();
		
		$("#cart-delete-dialog").css({
			"display": "block",
			"top": t,
			"left": l,
			"z-index": 1000
		});
		
		var remove = $(obj).parents("[class$='-quantity']").siblings("[class$='-remove']").children(".cart-remove");
		$("#btnRemoveConfirm").attr("data-bind",remove.attr("id"));
		$("#btnRemoveConfirm").attr("data-name",remove.attr("data-name"));
		$("#btnRemoveConfirm").attr("data-more",remove.attr("data-more"));
		
		return false;
	}else if(parseInt(num)<0){
		popupFormatWarningDialog(obj,"Quantity should be greater than 0!");
		return false;
	}else if(parseInt(num)>1000){
		popupFormatWarningDialog(obj,"Quantity should be less than 1000!");
		return false;
	}
	var ss =$(obj).attr("id").split("-");
	var pid = ss[1];
	/*if(checkBookeBuyLimit(pid,num)){
	    popupFormatWarningDialog(obj,"您购买的同一图书音像类商品数量不能大于5！");
		return  false;
	}*/
	popupLoadingDialog(obj);
	return true;
	
}

/**
 * 图书限购
 * @param pid
 * @param obj
 * @param num
 */
function checkBookeBuyLimit(pid,num){
	var pid=""+pid;
	if(checkSku(pid)){
		if(checkNumber(num)){
			if(pid.length == 8 && parseInt(num) > 5){
				return true;
			}
		}
	}
	return false;
}

/**
 * 增加商品数量+
 * @param obj
 */
function addSkuNum(obj){
	var ss =$(obj).attr("id").split("-");
	var pid = ss[1];
	var pcount = ss[2];
	var ptype = ss[3];
	var limit = ss[4];
	var targetId = 0;
	if(ss.length==6){
		targetId = ss[5];
	}
	var num = parseInt(pcount) + 1;
	var flag = isNumLegal(obj,num,limit);
	if(flag){
		if(checkRefreshCart(pid)){
			refreshCart();
			return ;
		}
		changeSkuNum("pid="+pid+"&pcount="+num+"&ptype="+ptype+"&targetId="+targetId);
	}else{//还原input值
		if(num != 0){
			$(obj).val(pcount);
		}
	}
}

/**
 * 减少商品数量-
 * @param obj
 */
function minusSkuNum(obj){
	var ss =$(obj).attr("id").split("-");
	var pid = ss[1];
	var pcount = ss[2];
	var ptype = ss[3];
	var targetId = 0;
	if(ss.length==5){
		targetId = ss[4];
	}
	var num = parseInt(pcount) - 1;
	var flag = isNumLegal(obj,num,0);
	if(flag){
		if(checkRefreshCart(pid)){
			refreshCart();
			return ;
		}
		changeSkuNum("pid="+pid+"&pcount="+num+"&ptype="+ptype+"&targetId="+targetId);
	}else{//还原input值
		if(num != 0){
			$(obj).val(pcount);
		}
	}
}

/**
 * 修改商品数量
 * @param obj
 * @returns {Boolean}
 */
function inputSkuNum(obj){
	var ss =$(obj).attr("id").split("-");
	var pid = ss[1];
	var pcount = ss[2];
	var ptype = ss[3];
	var limit = ss[4];
	var targetId = 0;
	var packId = 0;
	if(ss.length==6){
		targetId = ss[5];
	}
	if(ss.length==7){
		targetId = ss[5];
		packId = ss[6];
	}
	var num = $(obj).val();
	if(ptype == SkuItemType.YbOfSkusOrGifts || ptype == SkuItemType.YbOfPacks){
		var bindCount = $(obj).attr("bind-data"); 
		//延保商品数量不能超过它绑定的商品数量
		if(parseInt(num) > parseInt(bindCount)){
			popupYbWarningDialog(obj,"延保服务个数不能超过它绑定的商品个数！");
			$(obj).val(pcount);
			return false;
		}
	}
	
	var flag = isNumLegal(obj,num,limit);
	if(flag){
		/*if(checkBookeBuyLimit(pid,num)){
		    popupFormatWarningDialog(obj,"您购买的同一图书音像类商品数量不能大于5！");
			$(obj).val(pcount);
			return ;
		}*/
		if(ptype == SkuItemType.YbOfSkusOrGifts || ptype == SkuItemType.YbOfPacks){
			changeYbSkuNum("pid="+pid+"&pcount="+num+"&ptype="+ptype+"&targetId="+targetId+"&packId="+packId);
		}else{
			if(checkRefreshCart(pid)){
				refreshCart();
				return ;
			}
			changeSkuNum("pid="+pid+"&pcount="+num+"&ptype="+ptype+"&targetId="+targetId+"&packId="+packId);
		}
	}else{//还原input值
		if(num != 0){
			$(obj).val(pcount);
		}
	}
}

/**
 * 刷新购物车页面
 */
function refreshCart(){
	 window.location.href = PurchaseAppConfig.Domain+"/cart.html";
}

/**
 * 如果购物车cookie为空,或者商品不存在则刷新购物车
 * @returns
 */
function checkRefreshCart(skuId){
	  var cart=$.jCookie("cart-main");
	  cart = cart.replace(/\\/g,"");
	  cart = cart.replace(/\"/g,"");
	  if(cart == null || 
		 cart == "" ||
		 cart == "\"\"" ||
		 cart == "\"" ||
		 cart == "null"){
		  return true;
	  }
	  else{
		  var flag="&i&:"+skuId+"$";
		  var index=cart.indexOf(flag);
		  if(index == -1){
			  return true;
		  }
	  }
	  return false;
}

/**
 * 判断cookie是否为空
 * @returns {Boolean}
 */
function isEmptyCart(){
	 var cart=$.jCookie("cart-main");
	  cart = cart.replace(/\\/g,"");
	  cart = cart.replace(/\"/g,"");
	  if(cart == null || 
				 cart == "" ||
				 cart == "\"\"" ||
				 cart == "\"" ||
				 cart == "null"){
				  return true;
	  }
	  return false;
}


/**
 * 修改延保数量
 * @param param
 */
function changeYbSkuNum(param){
   call(PurchaseAppConfig.Domain+"/changeYbSkuNumInCart.action",param,"修改延保商品数量失败");
}

/**
 * 修改商品数量
 * @param param
 */
function changeSkuNum(param){
	call(PurchaseAppConfig.Domain+"/changeSkuNumInCart.action",param,"There was an error updating your item quantity");
}

/**
 * 添加赠品
 * @param pid
 * @param targetId
 * @param pcount
 */
function addGiftOfPacksToCart(pid,targetId,pcount){
	if(checkSku(pid)){
		var param = "pid="+pid+"&targetId="+targetId+"&ptype="+SkuItemType.SelectedGiftOfManZengPacks+"&pcount="+pcount;
		call(PurchaseAppConfig.Domain+"/addSkuToCartAsync.action",param,"添加赠品失败",initRecommendAndCollection);
	}else{
		 alert("对不起,您添加的赠品不存在");
	}
}

/**
 * 删除商品
 * @param pid
 * @param ptype
 * @param packId
 * @param targetId
 * @param callback
 */
function removeSku(pid,ptype,packId,targetId,callback){
	var actionUrl=null;
	if(checkSku(pid)){
	   if(ptype == SkuItemType.YbOfSkusOrGifts || ptype == SkuItemType.YbOfPacks){
			actionUrl=PurchaseAppConfig.Domain+"/removeYbSkuFromCart.action?rd="+Math.random();
		    updateCart(actionUrl,pid,ptype,packId,targetId,"删除延保商品失败",callback);
		}else{
			if(checkRefreshCart(pid) && (ptype != SkuItemType.SkuOfPacks)){
				refreshCart();
			}else{
				actionUrl=PurchaseAppConfig.Domain+"/removeSkuFromCart.action?rd="+Math.random();
				updateCart(actionUrl,pid,ptype,packId,targetId,"There was an error removing this item",callback);
			}  
		 }
	}
	else{
		 alert("Sorry, the deleted item does not exist!");
	}
}

/**
 * 批量删除购物车商品
 * @param callback
 */
function batchRemoveSkusFromCart(callback){
	if(isEmptyCart()){
		refreshCart();
	}else{
	   call(PurchaseAppConfig.Domain+"/batchRemoveSkusFromCart.action",null,"There was an error clearing your cart",callback);
	}
}

/**
 * 选中一个商品
 * @param pid
 * @param ptype
 * @param targetId
 */
function selectItem(pid,ptype,targetId){
	if(checkSku(pid)){
	   if(checkRefreshCart(pid)){
		  refreshCart();
	   }else{
			var actionUrl=PurchaseAppConfig.Domain+"/selectItem.action?rd"+Math.random();
		    updateCart(actionUrl,pid,ptype,0,targetId,"勾选商品失败",null);
	   }
	}else{
	   alert("对不起,您选择的商品不存在");
	}
}

/**
 * 取消选中一个商品
 * @param pid
 * @param ptype
 * @param targetId
 */
function cancelItem(pid,ptype,targetId){
	if(checkSku(pid)){
		if(checkRefreshCart(pid)){
			 refreshCart();
		  }else{
			var actionUrl=PurchaseAppConfig.Domain+"/cancelItem.action?rd"+Math.random();
		    updateCart(actionUrl,pid,ptype,0,targetId,"取消商品失败",null);
		  }
	}else{
		alert("对不起,您选择的商品不存在");
	}
}

/**
 * 全部选中商品
 */
function selectAllItem(){
	if(isEmptyCart()){
		refreshCart();
	}else{
		call(PurchaseAppConfig.Domain+"/selectAllItem.action",null,"全部勾选商品失败");
	}
}

/**
 * 反选中所有商品
 */
function cancelAllItem(){
	if(isEmptyCart()){
		refreshCart();
	}else{
		call(PurchaseAppConfig.Domain+"/cancelAllItem.action",null,"全部取消商品失败");
	}
}

function clearCurrentCart(){
	call(PurchaseAppConfig.Domain+"/clearCurrentCart.action",null,"There was an error clearing your cart");
}

/**
 * 重新购买商品,并绑定延保
 * @param id
 * @param type
 * @param num
 * @param packId
 * @param targetId
 */
function addSkuToCartReBuy(pid,ptype,num,packId,targetId){
	if(checkSku(pid)){
		var param = "pid="+pid+"&ptype="+ptype+"&pcount="+num+"&packId="+packId+"&targetId="+targetId;
		call(PurchaseAppConfig.Domain+"/addSkuToCartReBuy.action",param,"There was an error adding your item",initRecommendAndCollection);
	}else{
	   alert("Sorry, the item you would like to add does not exist");
	}
	
}

/**
 * 推荐商品加入购物车
 * @param id
 * @param type
 * @param num
 * @param packId
 * @param targetId
 */
function addSkuToCartAsync(pid,ptype,num,packId,targetId){
	if(checkSku(pid)){
	   var param = "pid="+pid+"&ptype="+ptype+"&pcount="+num+"&packId="+packId+"&targetId="+targetId;
	   call(PurchaseAppConfig.Domain+"/addSkuToCartAsync.action",param,"There was an error adding your item",initRecommendAndCollection);
	}
	else{
		alert("Sorry, the item you would like to add does not exist");
	}
}

/**
 * 增加延保商品
 * @param id
 * @param type
 * @param num
 * @param packId
 * @param targetId
 */
function addYbSkuToCart(pid,ptype,num,packId,targetId){
	if(checkSku(pid)){
	   var param = "pid="+pid+"&ptype="+ptype+"&pcount="+num+"&packId="+packId+"&targetId="+targetId;
	   call(PurchaseAppConfig.Domain+"/addYbSkuToCart.action",param,"增加延保失败",initRecommendAndCollection);
	}
	else{
		alert("对不起,您添加的商品不存在");
	}
	
}

function toggleSelected(){
	$("#toggle-checkboxes").click(function(){
		var selected = $(this).attr("checked");
		
		//点击复选框后所有复选框不可选
		$("input[type=checkbox]").attr("disabled",true);
		
		if(selected) {
			//把所有商品移到选中购物车
			selectAllItem();
		} else {
			//把所有商品移到未选中购物车
			cancelAllItem();
		}
	});
}

/**
 * 检查是否是数字
 * @param obj
 * @returns {Boolean}
 */
function checkNumber(obj){
	if(isNaN(obj)){
		return false;
	}
	try{
		var number=parseInt(obj);
         if(number > 0){
		    return true;
		 }	  
	}catch(e){}
	return false;
}

/**
 * 检查商品id
 * @param pid
 * @returns {Boolean}
 */
function checkSku(pid){
	 if(pid == null || pid == ""
		 || !checkNumber(pid)){
	    	return false;
	 }
	 else return true;
}


function toggleSingleSelected(){
	$('[data-bind*="cbid"]').click(function(){
		var cb = $(this).attr("checked");
		
		//点击复选框后所有复选框不可选
		$("input[type=checkbox]").attr("disabled",true);
		
		var cbID = $(this).attr("data-bind").replace("cbid:", "");
		var row = $('[data-bind="rowid:' + cbID + '"]');
		var arr = $(this).val().split("-");
		var pid = arr[0];
		var ptype = arr[1];
		var targetId = 0;
		if(arr.length == 3){
			targetId = arr[2];
		}
		
		if(cb) {
			//把商品移到选中购物车
			selectItem(pid,ptype,targetId);
		} else {
			//把商品移到未选中购物车
			cancelItem(pid,ptype,targetId);
		}
	});
}

/**
 * 执行统计代码
 */
function initWlJs(){
	var jdWlScript=document.createElement('script');
	jdWlScript.type='text/javascript';
	jdWlScript.src='http://wl.jd.com/wl.js';
	document.body.appendChild(jdWlScript);
}

/**
 * 海外购物去英文版购物车
 */
function toEnCart(){
    var cookie = readCartCookie("cart-main");
    var url = "http://jd2008.jd.com/purchase2/shoppingcart_en.aspx";
    if( cookie == null ){}
    else
    {
        var pattern = /\d{8}/ig;
        var result = cookie.match(pattern);
        var skus  = "";
        if( result ){
          for( i = 0; i < result.length; i++ ){
            if( skus.length > 0 )
                skus += ",";
            if(skus.indexOf(result[i])<0)
            	skus += result[i];
          }
        }
        if( skus.length > 0 )
        var url = "http://jd2008.jd.com/purchase/OrderFlowService.aspx?action=AddSkusEn&wids="+skus;
    }
    window.location.href = url;
}

/**
 * 获取cookie
 * @param b
 * @returns
 */
function readCartCookie(b){
    var e=b+"=";
    var a=document.cookie.split(";");
    for(var d=0;d<a.length;d++){
        var f=a[d];
        while(f.charAt(0)==" "){
                f=f.substring(1,f.length);
        }
        if(f.indexOf(e)==0){
            return f.substring(e.length,f.length);
        }
    }
    return null;
}

/**
 * 页面进入加载购物车
 */
$(document).ready(function(){
	if(!1 && !window.XMLHttpRequest) {
		try {document.execCommand("BackgroundImageCache", false, true);} catch(e){}
	}
	var outSkus = getParam("outSkus");
	$("#outSkus").val(outSkus);
	call(PurchaseAppConfig.Domain+"/getCurrentCartNew.action?rd="+Math.random(),null,null,function(){
//			initArea();
			initRecommendAndCollection();
			initWlJs();
	});
	
	$("#loadingcart").hide();
	$("#emptycart").hide();
	$("#productlist").show();
	
});